package view

import (
	"fmt"
	"parking-lot-go-dingding/model"
	"parking-lot-go-dingding/model/cars"
	"time"

	"gorm.io/gorm"
)

type MembersDingtalkViewStruct struct {
	MemberId                     int       `json:"member_id" gorm:"type:int(10) unsigned; NOT NULL;"`
	MemberMobile                 string    `json:"member_mobile" gorm:"type:varchar(20); COMMENT:'手机号码'"`
	MemberType                   string    `json:"member_type" gorm:"type:varchar(20); COMMENT:'会员类型 1固定会员 2临时停车'"`
	MemberRealName               string    `json:"member_real_name" gorm:"type:varchar(20); COMMENT:'会员名称'"`
	MemberAvatar                 string    `json:"member_avatar" gorm:"type:varchar(255); COMMENT:'头像'"`
	MemberExpiresTime            time.Time `json:"member_expires_time" gorm:"type:varchar(20); COMMENT:'过期时间'"`
	MemberRemarks                string    `json:"member_remarks" gorm:"type:varchar(100); COMMENT:'备注'"`
	MemberState                  int       `json:"member_state" gorm:"type:tinyint(1); COMMENT:'账号状态 1正常 2禁用 3过期'"`
	MemberAccountType            int       `json:"member_account_type" gorm:"type:tinyint(1); COMMENT:'账号类型 1钉钉 2微信'"`
	MemberAccountExtId           int       `json:"member_account_ext_id" gorm:"type:int(11); COMMENT:'账号扩展id'"`
	MemberCreatedAt              time.Time `json:"member_created_at" gorm:"type:datetime"`
	MemberUpdatedAt              time.Time `json:"member_updated_at" gorm:"type:datetime"`
	MemberAvailableParking       string    `json:"member_available_parking" gorm:"type:text; COMMENT:'停车场'"`
	MemberMoney                  float64   `json:"member_money" gorm:"type:decimal(10,2);  COMMENT:'可用余额'"`
	MemberIsVip                  int       `json:"member_is_vip" gorm:"type:tinyint(1);  COMMENT:'是否vip 1是 0否'"`
	MemberDingtalkId             int       `json:"member_dingtalk_id" gorm:"type:int(11); NOT NULL;"`
	MemberDingtalkCorpid         string    `json:"member_dingtalk_corpid" gorm:"type:varchar(50); COMMENT:'组织架构id'"`
	MemberDingtalkDepartmentId   string    `json:"member_dingtalk_department_id" gorm:"type:varchar(20); "`
	MemberDingtalkDepartmentName string    `json:"member_dingtalk_department_name" gorm:"type:varchar(50); COMMENT:'部门'"`
	MemberDingtalkUserid         string    `json:"member_dingtalk_userid" gorm:"type:varchar(20); COMMENT:'用户id'"`
	MemberDingtalkFromUserid     string    `json:"member_dingtalk_from_userid" gorm:"type:varchar(32); COMMENT:'添加人ding user id'"`
	MemberDingtalkPosition       string    `json:"member_dingtalk_position" gorm:"type:varchar(50); COMMENT:'职位'"`
	MemberDingtalkCreatedAt      time.Time `json:"member_dingtalk_created_at" gorm:"type:datetime"`
	MemberDingtalkUpdatedAt      time.Time `json:"member_dingtalk_updated_at" gorm:"type:datetime"`
}

func (c *MembersDingtalkViewStruct) TableName() string {
	return "members_dingtalk_view"
}

func (c *MembersDingtalkViewStruct) First(where map[string]interface{}) (MembersDingtalkViewStruct, error) {
	var membersDingtalkViewStruct MembersDingtalkViewStruct
	db := model.Db
	if err := db.
		Table(c.TableName()).
		Where(where).
		First(&membersDingtalkViewStruct).
		Error; err != nil {
		return membersDingtalkViewStruct, err
	}
	return membersDingtalkViewStruct, nil
}

func (c *MembersDingtalkViewStruct) SearchAndCount(accountType, accountState, keyword, sortParams string, sortType, start, limit int) ([]MembersDingtalkViewStruct, int64, error) {
	var memberList []MembersDingtalkViewStruct

	var count int64

	db := model.Db.Table(c.TableName()).Debug()

	//账号类型
	if accountType != "" {
		db = db.Where("member_type", accountType)
	}

	//账号状态
	if accountState != "" {
		db = db.Where("member_state", accountState)
	}

	//车牌 or 姓名
	if keyword != "" {
		var carsStruct cars.CarsStruct
		memberIds, err := carsStruct.CarNumberFind(keyword)
		if err != nil {
			return memberList, 0, err
		}

		db = db.Where("member_real_name like ? or member_id in (?)", "%"+accountState+"%", memberIds)
	}

	//排序规则
	if sortParams == "" {
		sortParams = "asc"
	}

	switch sortType {
	case 1:
		db = db.Order(fmt.Sprintf("member_updated_at %s, member_id %s", sortParams, sortParams))
	case 3:
		db = db.Order(fmt.Sprintf("member_money %s, member_id %s", sortParams, sortParams))
	default:
		db = db.Order("member_updated_at desc")
	}

	if err := db.Offset(start).Limit(limit).Scan(&memberList).Error; err != nil && err != gorm.ErrRecordNotFound {
		return memberList, 0, err
	}

	// 统计总数
	if err := db.Count(&count).Error; err != nil && err != gorm.ErrRecordNotFound {
		return nil, 0, err
	}

	return memberList, 0, nil
}

func (c *MembersDingtalkViewStruct) Count(where map[string]interface{}) (int64, error) {

	var count int64

	if err := model.Db.Table(c.TableName()).Where(where).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}
